package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {
    @Autowired
    private CheckGroupDao checkGroupDao;
    
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        checkGroupDao.add(checkGroup);
        Integer checkGroupId = checkGroup.getId();
        setCheckGroupAndCheckItem(checkitemIds, checkGroupId);
    }
    
    private void setCheckGroupAndCheckItem(Integer[] checkitemIds, Integer checkGroupId) {
        if (checkitemIds != null && checkitemIds.length > 0) {
            for (Integer checkitemId : checkitemIds) {
                Map<String, Integer> map = new HashMap<String, Integer>();
                map.put("checkgroupId", checkGroupId);
                map.put("checkitemId", checkitemId);
                checkGroupDao.setCheckGroupAndCheckItem(map);
            }
        }
    }
    
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer pageSize = queryPageBean.getPageSize();
        Integer currentPage = queryPageBean.getCurrentPage();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<CheckGroup> page = checkGroupDao.findByCondition(queryString);
        List<CheckGroup> rows = page.getResult();
        long total = page.getTotal();
        return new PageResult(total, rows);
    }
    
    @Override
    public CheckGroup findById(Integer id) {
        CheckGroup checkGroup = checkGroupDao.findById(id);
        System.out.println(checkGroup);
        return checkGroup;
    }
    
    @Override
    public List<Integer> findcheckitemIdsByCheckGroupId(Integer id) {
        return checkGroupDao.findcheckitemIdsByCheckGroupId(id);
    }
    
    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        //修改checkGroup数据
        checkGroupDao.edit(checkGroup);
        //根据id删除原有的数据关联
        checkGroupDao.deleteAssocication(checkGroup.getId());
        //插入新的数据关联
        setCheckGroupAndCheckItem(checkitemIds, checkGroup.getId());
    }
    
    @Override
    public void delete(Integer id) {
        checkGroupDao.deleteAssocication(id);
//        checkGroupDao.deleteAssocicationWithSetmeal(id);
        checkGroupDao.delete(id);
    }
    
    @Override
    public List<CheckGroup> findAll() {
        return checkGroupDao.findAll();
    }
}
